package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.HasPermi;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.dao.SysMenu;
import com.ruoyi.system.domain.query.SysMenuQo;
import com.ruoyi.system.domain.wrapper.query.SysMenuWrapperQ;
import com.ruoyi.system.service.ISysMenuService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 菜单权限Controller
 *
 * @author 尹国春
 * @date 2022-07-26
 */
@Api(value = "菜单权限", tags = {"菜单权限"})
@RestController
@RequestMapping("/system/menu")
public class SysMenuController extends BaseController {
    @Autowired
    private ISysMenuService menuService;

    /**
     * 获取菜单列表
     */
    @HasPermi("system:menu:list")
    @GetMapping("/list")
    public AjaxResult list(SysMenuQo menu) {
        if (!SecurityUtils.isAdmin(getUserId())) {
            menu.setUserId(getUserId());
        }
        List<SysMenu> menus = menuService.list(SysMenuWrapperQ.getQueryWrapper(menu).orderByAsc(SysMenu::getOrderNum));
        return AjaxResult.success(menus);
    }

    /**
     * 根据菜单编号获取详细信息
     */
    @HasPermi("system:menu:list")
    @GetMapping(value = "/{menuId}")
    public AjaxResult getInfo(@PathVariable String menuId) {
        return AjaxResult.success(menuService.getById(menuId));
    }

    /**
     * 获取菜单下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(SysMenuQo menu) {
        if (!SecurityUtils.isAdmin(getUserId())) {
            menu.setUserId(getUserId());
        }
        List<SysMenu> menus = menuService.list(SysMenuWrapperQ.getQueryWrapper(menu));
        return AjaxResult.success(menuService.buildMenuTreeSelect(menus));
    }

    /**
     * 加载对应角色菜单列表树
     */
    @GetMapping(value = "/roleMenuTreeselect/{roleId}")
    public AjaxResult roleMenuTreeselect(@PathVariable("roleId") String roleId) {
        SysMenuQo menu = new SysMenuQo();
        if (!SecurityUtils.isAdmin(getUserId())) {
            menu.setUserId(getUserId());
        }
        List<SysMenu> menus = menuService.list(SysMenuWrapperQ.getQueryWrapper(menu).orderByAsc(SysMenu::getOrderNum));
        Map<String, Object> data = new HashMap<>();
        data.put("checkedKeys", menuService.selectMenuListByRoleId(roleId));
        data.put("menus", menuService.buildMenuTreeSelect(menus));
        return AjaxResult.success(data);
    }

    /**
     * 新增菜单
     */
    @HasPermi("system:menu:edit")
    @Log(title = "菜单管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody SysMenu menu) {
        if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) {
            return AjaxResult.error("新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        } else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath())) {
            return AjaxResult.error("新增菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        return toAjax(menuService.insert(menu));
    }

    /**
     * 修改菜单
     */
    @HasPermi("system:menu:edit")
    @Log(title = "菜单管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(@Validated @RequestBody SysMenu menu) {
        if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) {
            return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        } else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath())) {
            return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        } else if (menu.getMenuId().equals(menu.getParentId())) {
            return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败，上级菜单不能选择自己");
        }
        menu.setUpdateBy(getUsername());
        return toAjax(menuService.updateById(menu));
    }

    /**
     * 删除菜单
     */
    @HasPermi("system:menu:edit")
    @Log(title = "菜单管理", businessType = BusinessType.DELETE)
    @PostMapping("/delete/{menuId}")
    public AjaxResult remove(@PathVariable("menuId") String menuId) {
        if (menuService.hasChildByMenuId(menuId)) {
            return AjaxResult.error("存在子菜单,不允许删除");
        }
        if (menuService.checkMenuExistRole(menuId)) {
            return AjaxResult.error("菜单已分配,不允许删除");
        }
        return toAjax(menuService.removeById(menuId));
    }
}